package com.kj.tms.system.service.basicinfo.serviceImpl;


import com.kj.tms.common.bean.dao.BaseMapper;
import com.kj.tms.common.bean.dto.Pager;
import com.kj.tms.common.bean.dto.ReturnData;
import com.kj.tms.common.bean.service.BaseService;
import com.kj.tms.common.bean.session.SessionManager;
import com.kj.tms.common.utils.StringUtil;
import com.kj.tms.common.utils.constant.Consts;
import com.kj.tms.common.utils.uuid.IdGen;
import com.kj.tms.pri.system.basicinfo.dto.ShareholderDto;
import com.kj.tms.pri.system.basicinfo.dto.TaxIdentifyDto;
import com.kj.tms.pri.system.basicinfo.dto.TaxPayersInfoDto;
import com.kj.tms.pri.system.basicinfo.service.TaxPayersInfoService;
import com.kj.tms.pri.system.user.dto.UserDto;
import com.kj.tms.system.service.basicinfo.dao.BaseMessageMapper;
import com.kj.tms.system.service.basicinfo.dao.TaxIdentifyMapper;
import com.kj.tms.system.service.basicinfo.dao.TaxPayersInfoMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import net.sf.json.JSONArray;

import java.util.*;

/**
 * @author dongshidong
 * @ProjectName: tms
 * @Package: com.hongtu.tms.basicinfo.service.impl
 * @ClassName: TaxPayersInfoServiceImpl
 * @Description: 纳税主体TaxPayersInfoServiceImpl
 * @CreateDate: 2017/11/08 9:38
 * @UpdateUser:
 * @UpdateDate:
 * @UpdateRemark:
 * @Version: 1.0
 * Copyright: 北京宏图天安 Copyright (c) 2017
 */
@Service
@Transactional
public class TaxPayersInfoServiceImpl extends BaseService<TaxPayersInfoDto>
        implements TaxPayersInfoService {

    @Autowired
    private TaxPayersInfoMapper taxPayersInfoMapper;

    @Autowired
    private SessionManager sessionManager;

    @Autowired
    private TaxIdentifyMapper taxIdentifyMapper;

    @Autowired
    private BaseMessageMapper baseMessageMapper;
    @Override
    public BaseMapper<TaxPayersInfoDto> getMapper() {
        return taxPayersInfoMapper;
    }

    //增值税税种
    private  final String taxCodeVat = "01";
    //所得税税种
    private  final String taxCodeInComeTax = "04";
    // 是否插入标志
    private  final String isInsertMark = "false";


    /**
     * @param model model
     * @return Pager
     * @throws
     * @method queryByPage
     * @description 查询分页数据
     * @author 董世栋
     * @version 1.0
     * @date
     */
    @Override
    public Pager queryByPage(@RequestBody(required = false) TaxPayersInfoDto model) {

        if (StringUtil.isNull(model.getOrgCode())) {
            UserDto user = (UserDto) sessionManager.getAttribute(Consts.USER);
            if (user != null) {
                model.setOrgCode(user.getCurUserOrgCode());
            }
        }

        model.setValidMark(Consts.VALID_MARK_1);
        model.setDelMark(Consts.DEL_MARK_0);
        return super.selectPage(model);
    }

    /**
     * @param curOrgCode 当前登录机构
     * @return List<TaxPayersInfoDto>
     * @throws
     * @method [queryListByOrgCode]
     * @description [通过当前机构查询纳税主体]
     * @author 王国庆
     * @version 1.0
     * @date 2017年11月08日 19:25`
     */
    @Override
    public List<TaxPayersInfoDto> queryListByOrgCode(@RequestParam("curOrgCode") String curOrgCode) {
        return taxPayersInfoMapper.queryListByOrgCode(curOrgCode);
    }

    /**
     * @param dto dto
     * @return TaxPayersInfoDto
     * @throws
     * @method insertDto
     * @description 添加数据
     * @author 董世栋
     * @version 1.0
     * @date
     */
    @Override
    public ReturnData insertDto(@RequestBody(required = false) TaxIdentifyDto dto) {
        ReturnData rtn = new ReturnData();
        // 检查税号是否重复
        rtn = getByCode(dto);
        if (rtn.getCode().equals(Consts.ERROR)) {
            return rtn;
        }

        // 通过组织编码查询是否已经绑定过组织
        rtn = getByOrgCode(dto, "true");
        if (rtn.getCode().equals(Consts.ERROR)) {
            return rtn;
        }

        // 设置用户信息
        UserDto user = (UserDto) sessionManager.getAttribute(Consts.USER);
        if (user != null) {
            if (StringUtils.isBlank(dto.getId())) {
                dto.setCreateUser(user.getUserId());
            }
        }
        dto.setValidMark(Consts.VALID_MARK_1);
        dto.setDelMark(Consts.DEL_MARK_0);
        dto.setId(IdGen.getId());
        dto.setCreateTime(new Date());
        taxPayersInfoMapper.insert(dto);

        //保存股东信息
        List<ShareholderDto> shareholderList=dtoToShareholderList(dto);
        if(shareholderList.size()>0){
            taxIdentifyMapper.batchInsertShareholder(shareholderList);
        }

        //保存税种鉴定信息
        List list = dtoToTaxIdentifyDto(dto);
        taxIdentifyMapper.batchInsert(list);
        return rtn;
    }


    public List<ShareholderDto> dtoToShareholderList(@RequestBody(required = false) TaxIdentifyDto dto){

        JSONArray array = JSONArray.fromObject(dto.getShareholderDto().toString());
        List<ShareholderDto> shareholderList=(List)JSONArray.toCollection(array, ShareholderDto.class);
        if(shareholderList.size()>0){
            for(int i =0 ;i< shareholderList.size();i++){
                shareholderList.get(i).setId(IdGen.getId());
                shareholderList.get(i).setTaxpayersinfo(dto.getId());
                shareholderList.get(i).setDelmark("0");
            }

        }
        return shareholderList;
    }
    /**
     * @param
     * @return
     * @throws
     * @method updateByPrimary
     * @description
     * @author 董世栋
     * @version 1.0
     * @date
     */
    @Override
    public ReturnData updateByPrimary(@RequestBody(required = false) TaxIdentifyDto dto) {
        ReturnData rtn = new ReturnData();

        // 通过组织编码查询是否已经绑定过组织
        rtn = getByOrgCode(dto, "false");
        if (rtn.getCode().equals(Consts.ERROR)) {
            return rtn;
        }

        // 设置用户信息
        UserDto user = (UserDto) sessionManager.getAttribute(Consts.USER);
        if (user != null) {
            dto.setUpdateUser(user.getUserId());
            dto.setUpdateTime(new Date());
        }
        taxPayersInfoMapper.updateByPrimary(dto);

        // 查询税种鉴定信息
        List<TaxIdentifyDto> taxIdentifyDtoList = taxIdentifyMapper.getByPrimaryKey(dto.getId());
        // 插入或者更新税种鉴定信息
        if (StringUtil.isNotNull(taxIdentifyDtoList)) {
            List list = dtoToTaxIdentifyDto(dto);
            if(StringUtil.isNotNull(list)){
                // 删除旧关系
                taxIdentifyMapper.deleteByPrimaryKey(taxIdentifyDtoList.get(0).getTaxpayersInfoId());
                taxIdentifyMapper.batchInsert(list);
            }
        } else {
            // 初始化只维护纳税主体信息，后期补充税种鉴定情况
            List list = dtoToTaxIdentifyDto(dto);
            if(StringUtil.isNotNull(list)){
                taxIdentifyMapper.batchInsert(list);
            }

        }
        rtn.setCode(Consts.SUCCESS);
        rtn.setMsg("保存成功");
        return rtn;
    }

    /**
     * @Method      updateByPrimary
     * @Param       [orgCode]
     * @Return      com.hongtu.tms.basebean.basedata.ReturnData
     * @Exception
     * @Description [解除组织和纳税主体关系]
     * @Author      dsd
     * @Version     1.0
     * @Date        2018/1/31 18:04
     */
    @Override
   public ReturnData updateToDelOrgRelease(@RequestParam("orgCode") String orgCode ){
        ReturnData rtn = new ReturnData();
        taxPayersInfoMapper.updateToDelOrgRelease(orgCode);
        rtn.setCode(Consts.SUCCESS);
        rtn.setMsg("保存成功");
        return rtn;
    }
    /**
     * @Method      batchInsertShareholder
     * @Param
     * @Return
     * @Exception
     * @Description [批量更新股东信息]
     * @Author      yangruidong
     * @Version     1.0
     * @Date        2018/5/24 17:11
     */
    @Override
    public void batchInsertShareholder(@RequestBody List<ShareholderDto> list) {
        taxIdentifyMapper.batchInsertShareholder(list);
    }

    @Override
    public TaxIdentifyDto judgeIsParent(@RequestParam("orgCode") String orgCode, @RequestParam("taxCode")String taxCode) {
        return taxIdentifyMapper.judgeIsParent(orgCode,taxCode);
    }

    /**
     * @param dto
     * @return
     * @throws
     * @method dtoToTaxIdentifyDto
     * @description controller传入dto转 TaxIdentifyDto
     * @author 董世栋
     * @version 1.0
     * @date
     */
    private List<Map> dtoToTaxIdentifyDto(TaxIdentifyDto dto) {
        List list = new ArrayList();
        String taxCode = dto.getTaxcode();
        if(StringUtil.isNotNull(taxCode)){
            String[] taxCodes = taxCode.split(",");
            for (int i = 0, len = taxCodes.length; i < len; i++) {
                if (taxCodes[i].equals(taxCodeInComeTax)) {
                    // 所得税税种
                    Map map = new HashMap<String, String>();
                    map.put("id", IdGen.getId());
                    map.put("taxpayersInfoId", dto.getId());
                    map.put("taxcode", taxCodes[i]);
                    map.put("gatherTypeIncomeTax", dto.getGatherTypeIncomeTax());
                    map.put("collectTypeIncomeTax", dto.getCollectTypeIncomeTax());
                    map.put("payTaxType", null);
                    map.put("gatherTypeVat", null);
                    map.put("collectTypeLandTax", null);
                    map.put("declareCycle", dto.getDeclareCycleChk());
                    list.add(map);
                } else if (taxCodes[i].equals(taxCodeVat)) {
                    // 增值税税种
                    Map map = new HashMap<String, String>();
                    map.put("id", IdGen.getId());
                    map.put("taxpayersInfoId", dto.getId());
                    map.put("taxcode", taxCodes[i]);
                    map.put("gatherTypeVat", null);
                    map.put("gatherTypeIncomeTax", dto.getGatherTypeVat());
                    map.put("collectTypeIncomeTax", null);
                    map.put("payTaxType", null);
                    map.put("collectTypeLandTax", null);
                    map.put("declareCycle", dto.getDeclareCycleVatChk());
                    list.add(map);
                } else {
                    //其他税种
                    Map map = new HashMap<String, String>();
                    map.put("id", IdGen.getId());
                    map.put("taxpayersInfoId", dto.getId());
                    map.put("taxcode", taxCodes[i]);
                    map.put("gatherTypeIncomeTax", null);
                    map.put("collectTypeIncomeTax", null);
                    map.put("payTaxType", null);
                    map.put("gatherTypeVat", null);
                    map.put("collectTypeLandTax", null);
                    map.put("declareCycle", null);
                    list.add(map);
                }
            }
            return list;
        }

        return null;
    }


    /**
     * @param dto sd
     * @return int
     * @throws
     * @method deleteTaxPayersInfo
     * @description 删除纳税主体信息及税种鉴定信息
     * @author 董世栋
     * @version 1.0
     * @date
     */
    @Override
    public ReturnData deleteTaxPayersInfo(@RequestBody(required = false) TaxPayersInfoDto dto) {
        ReturnData rtn = new ReturnData();
        // 设置用户信息
        UserDto user = (UserDto) sessionManager.getAttribute(Consts.USER);
        if (user != null) {
            dto.setUpdateUser(user.getUserId());
            dto.setUpdateTime(new Date());
        }
        taxPayersInfoMapper.updateByPrimary(dto);

        // 删除税种鉴定信息
        taxIdentifyMapper.deleteByPrimaryKey(dto.getId());

        //删除 股东信息
        ShareholderDto sareholderDto = new ShareholderDto();
        sareholderDto.setTaxpayersinfo(dto.getId());
        sareholderDto.setDelmark(Consts.DEL_MARK_1);
        baseMessageMapper.updateShareholder(sareholderDto);
//        baseMessageMapper.updateA0000002(sareholderDto);

        rtn.setCode(Consts.SUCCESS);
        rtn.setMsg("删除纳税主体成功");
        return rtn;
    }

    /**
     * @param
     * @return
     * @throws
     * @method getByPrimaryKey
     * @description 主键查询纳税主体
     * @author 董世栋
     * @version 1.0
     * @date
     */
    @Override
    public TaxIdentifyDto getByPrimaryKey(@RequestParam("id") String id) {
        TaxPayersInfoDto taxPayersInfoDto = taxPayersInfoMapper.getByPrimaryKey(id);

        TaxIdentifyDto dto = new TaxIdentifyDto();
        // 转换dto
        BeanUtils.copyProperties(taxPayersInfoDto, dto);
        List<TaxIdentifyDto> taxIdentifyDtoList = taxIdentifyMapper.getByPrimaryKey(id);
        StringBuffer taxCode = new StringBuffer() ;
        for (int i = 0; i < taxIdentifyDtoList.size(); i++) {
            if (StringUtil.isNotNull(taxIdentifyDtoList.get(i).getGatherTypeIncomeTax())) {
                if (taxCodeInComeTax.equals(taxIdentifyDtoList.get(i).getTaxcode())) {
                    //所得税
                    dto.setGatherTypeIncomeTax(taxIdentifyDtoList.get(i).getGatherTypeIncomeTax());
                    dto.setCollectTypeIncomeTax(taxIdentifyDtoList.get(i).getCollectTypeIncomeTax());
                    dto.setDeclareCycleChk(taxIdentifyDtoList.get(i).getDeclareCycle());
                }
                if (taxCodeVat.equals(taxIdentifyDtoList.get(i).getTaxcode())) {
                    //增值税
                    dto.setGatherTypeVat(taxIdentifyDtoList.get(i).getGatherTypeIncomeTax());
                    dto.setDeclareCycleVatChk(taxIdentifyDtoList.get(i).getDeclareCycle());
                }
            }
            taxCode = taxCode.append(",").append(taxIdentifyDtoList.get(i).getTaxcode());
        }
        dto.setTaxcode(taxCode.toString());
        return dto;
    }

    /**
     * @Method getByCode
     * @Param dto
     * @Return ReturnData
     * @Exception
     * @Description [通过税号查询纳税主体税号是否重复]
     * @Author dsd
     * @Version 1.0
     * @Date 2017/11/23 11:37
     */
    private ReturnData getByCode(TaxPayersInfoDto dto) {
        ReturnData rtn = new ReturnData();
        List<String> code = taxPayersInfoMapper.getByCode(dto.getCode());
        if (StringUtil.isNotNull(code)) {
            rtn.setCode(Consts.ERROR);
            rtn.setMsg("统一社会信用代码/纳税人识别号重复，保存失败");
        } else {
            rtn.setCode(Consts.SUCCESS);
            rtn.setMsg("保存成功");
        }
        return rtn;
    }

    /**
     * @Method getByOrgCode
     * @Param dto, isInsert
     * @Return ReturnData
     * @Exception
     * @Description [通过组织编码查询是否已经绑定过组织]
     * @Author dsd
     * @Version 1.0
     * @Date 2017/11/23 11:37
     */
    private ReturnData getByOrgCode(TaxPayersInfoDto dto, String isInsert) {
        ReturnData rtn = new ReturnData();
        List<TaxPayersInfoDto> code = taxPayersInfoMapper.getByOrgCode(dto.getOrgCode());
        if (StringUtil.isNotNull(code)) {
            if (isInsertMark.equals(isInsert)) {
                //修改
                if (code.size() > 1) {
                    rtn.setCode(Consts.ERROR);
                    rtn.setMsg("该组织已经关联其他纳税主体，关联税号为：" + code.get(0).getCode() + "，请选择其他组织");
                } else {
                    rtn.setCode(Consts.SUCCESS);
                    rtn.setMsg("保存成功");
                }
            } else {
                rtn.setCode(Consts.ERROR);
                rtn.setMsg("该组织已经关联其他纳税主体，关联税号为：" + code.get(0).getCode() + "，请选择其他组织");
            }
        } else {
            rtn.setCode(Consts.SUCCESS);
            rtn.setMsg("保存成功");
        }
        return rtn;
    }
}
